var kit = require('./kit')
var vdom = require('./vdom')
var CONST = kit.CONST

/*      My array html    */
/*
表现形式
1 ['div.left.clear#id',{attr},{type:child,child:[x]}] -> VDOM
2 ['div.left.clear#id',{attr},['div.child','xxx'],['div.child','xxx2']...] -> VDOM
其中attr可以省略
Atml -> VirtualDom
*/
function arrhtml(ahtml){
  return arrhtmlBy(function(a){return a},ahtml)
}
/**
  (VDOM -> VDOM) -> [html] -> VDOM
*/
function arrhtmlBy(fn,ahtml){
  if(isBoolean(ahtml)){
    return fn({
      type:CONST.VTEXT,
      val:''
    })
  }else if(isString(ahtml)){
    return fn({
      type:CONST.VTEXT,
      val:ahtml
    })
  }else if(isNumber(ahtml)){
    return fn({
      type:CONST.VTEXT,
      val:ahtml.toString()
    })
  }else if(isArray(ahtml)){
    if(isFunction(ahtml[0])){
      var fnhtml = ahtml[0]
      var msg = ahtml[1]
      return arrhtmlBy(function(vdom){
        for(var key in vdom.attr){
          var val = vdom.attr[key]
          if(kit.isMsg(val)){
            vdom.attr[key] = msg.concat([val])
          }else{
            void null
          }
        }
        return fn(vdom)
      },fnhtml(ahtml[2],ahtml[3],ahtml[4]))
    }else{
      var obj = parserTag(ahtml[0])
      var attr = {}
      var child = []
      if(isaChild(ahtml[1])){
        attr.className = obj.className
        attr.id = obj.id
        child = fetchChild(fn,ahtml.slice(1))
      }else if(isObject(ahtml[1])){
        attr = ahtml[1]
        attr.className = obj.className
        attr.id = obj.id
        child = fetchChild(fn,ahtml.slice(2))
      }else{
        attr.className = obj.className
        attr.id = obj.id
        child = fetchChild(fn,ahtml.slice(1))
      }
      return fn({
        type:CONST.VDOM,
        name:obj.name,
        attr:attr,
        child:child
      })
    }
  }else{
    return fn({
      type:CONST.VTEXT,
      val:''
    })
  }
}
function fetchChild(fn,xs){
  var r =[]
  for(var i=0;i<xs.length;i++){
    if(isaChild(xs[i])){
      r = r.concat(xs[i].child.map(function(x){return arrhtmlBy(fn,x)}))
    }else{
      r.push(arrhtmlBy(fn,xs[i]))
    }
  }
  return r
}
function sub(xs){
  return {
    type:CONST.CHILD,
    child:xs
  }
}
function isaChild(a){
  return a&&a.type == CONST.CHILD
}
/*   My render */
function createRender(div){
  var lastvdom 
  // ahtml -> ()
  return function(ahtml,baseVDom){
    time('render')
    var cvdom
    if(isVDOM(ahtml)){
      cvdom = ahtml
    }else{
      cvdom = arrhtml(ahtml)
    }
    if(baseVDom != null){
      lastvdom = baseVDom
    }else{
      void null
    }
    if(lastvdom){
      var patchs = diff(lastvdom,cvdom)
      updatePatch(patchs)
      lastvdom = cvdom
    }else{
      var dom = renderVDOM(cvdom)
      lastvdom = cvdom
      div.appendChild(dom)
    }
    timeEnd('render')
    return cvdom
  }
}

module.exports = {
  createRender:createRender,
  arrhtml:arrhtml
}
